package com.weitu.contractor.controller;

import com.weitu.accessory.bean.AccessoryPackageInfo;
import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.accessory.util.AccessoryUtil;
import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.contractor.entity.ManagerAudit;
import com.weitu.contractor.entity.ManagerAuditCriteria;
import com.weitu.contractor.service.ContractorAuditService;
import com.weitu.contractor.service.ContractorStaffService;
import com.weitu.contractor.service.ManagerAuditService;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.dataAuthority.service.DataAuthorityService;
import com.weitu.plugin.PageView;
import com.weitu.threeSimultaneities.projectInfo.entity.Project;
import com.weitu.threeSimultaneities.projectInfo.service.ProjectService;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * @author LiMeng 2017/4/21
 */
@Controller
@RequestMapping(value = "contractor/managerAudit")
public class ManagerAuditController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "contractor/managerAudit";
    private final ManagerAuditService managerAuditService;
    private final ProjectService projectService;
    private final ContractorAuditService contractorAuditService;
    private final ContractorStaffService contractorStaffService;
    private final DataAuthorityService dataAuthorityService;
    private final AccessoryUtilService accessoryUtilService;

    @Autowired
    public ManagerAuditController(ManagerAuditService managerAuditService
            , ProjectService projectService
            , ContractorAuditService contractorAuditService
            , ContractorStaffService contractorStaffService
            , DataAuthorityService dataAuthorityService
            , AccessoryUtilService accessoryUtilService) {
        this.managerAuditService = managerAuditService;
        this.projectService = projectService;
        this.contractorAuditService = contractorAuditService;
        this.contractorStaffService = contractorStaffService;
        this.dataAuthorityService = dataAuthorityService;
        this.accessoryUtilService = accessoryUtilService;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() {
        return MODULE_BATH_PATH + "/list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute("uploadUserId", getSessionUser().getId());
        return MODULE_BATH_PATH + "/add";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, String id) {
        putAttributesIntoModel(model, id);
        return MODULE_BATH_PATH + "/edit";
    }

    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(Model model, String id) {
        putAttributesIntoModel(model, id);
        return MODULE_BATH_PATH + "/edit";
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Object listAjax(HttpServletRequest request, String sort) throws Exception {
        ManagerAuditCriteria criteria = new ManagerAuditCriteria();
        ManagerAuditCriteria.Criteria cr = criteria.createCriteria()
                .andDelStateEqualTo(0);
        putSearchCriteria(cr);
        int count = managerAuditService.countByCriteria(criteria);

        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        //未传sort参数是采用添加时间排序
        if (StringUtils.isEmpty(sort)) {
            pageView.setSortColumn("addTime");
        } else {
            criteria.setOrderByClause(pageView.getSortColumn() + " " + pageView.getOrderType());
        }
        criteria.setPageView(pageView);

        List<ManagerAudit> managerAudits = managerAuditService.selectByCriteria(criteria);

        return dataGridPagination.flushDataGridData(managerAudits);
    }

    @SystemLog(module = "项目经理资质审查", methods = "删除项目经理资质审查信息")
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult deleteAjax(String id) throws Exception {
        if (managerAuditService.deleteByPrimaryKey(id) > 0) {
            return success("删除成功！");
        } else {
            return fail("删除失败！");
        }
    }

    @SystemLog(module = "项目经理资质审查", methods = "新增项目经理资质审查信息")
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public AjaxResult addAjax(ManagerAudit managerAudit) throws Exception {
        if (managerAuditService.checkIfExist(managerAudit.getContractorAuditId(), managerAudit.getManagerId(), managerAudit.getProjectId())) {
            return fail("已有相同的数据，请重新选择！");
        }
        String id = IDGenerator.getId();
        managerAudit.setId(id);
        managerAudit.setAddUserId(getSessionUser().getId());
        managerAudit.setAddDeptId(getSessionUser().getDepartment().getId());
        managerAudit.setAddTime(DateTimeUtil.formatterDateTime());
        if (AccessoryUtil.saveAccerssoryInfo(id)) {
            if (managerAuditService.insertSelective(managerAudit) > 0) {
                return success("保存成功！", managerAudit);
            }
            return fail("保存失败！");
        }
        return fail("附件信息保存失败！");
    }

    @SystemLog(module = "项目经理资质审查", methods = "更新项目经理资质审查信息")
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @Transactional
    public AjaxResult editAjax(ManagerAudit managerAudit) throws Exception {
        if (managerAuditService.checkIfExist(managerAudit.getContractorAuditId(),
                managerAudit.getManagerId(),
                managerAudit.getProjectId(),
                managerAudit.getId())) {
            return fail("已有相同的数据，请重新选择！");
        }
        managerAudit.setUpdateUserId(getSessionUser().getId());
        managerAudit.setUpdateDeptId(getSessionUser().getDepartment().getId());
        managerAudit.setUpdateTime(DateTimeUtil.formatterDateTime());
        if (AccessoryUtil.saveAccerssoryInfo(managerAudit.getId())) {
            if (managerAuditService.updateByPrimaryKeySelective(managerAudit) > 0) {
                return success("保存成功！", managerAudit);
            }
            return fail("保存失败！");
        }
        return fail("附件信息保存失败！");

    }

    private void putAttributesIntoModel(Model model, String id) {
        ManagerAudit managerAudit = managerAuditService.selectByPrimaryKey(id);
        List<AccessoryPackageInfo> accessoryList = accessoryUtilService.queryAccessoryByBusinessId(id);
        Project project = projectService.selectById(managerAudit.getProjectId());
        model.addAttribute("managerAudit", managerAudit);
        model.addAttribute("accessoryList", accessoryList);
        model.addAttribute("project", project);
        model.addAttribute("uploadUserId", getSessionUser().getId());
    }

    /**
     * 添加查询条件
     *
     * @param criteria 条件
     */
    private void putSearchCriteria(ManagerAuditCriteria.Criteria criteria) {
        if (StringUtils.isNotEmpty(getPara("contractorName"))) {
            List<String> contractorAuditIds = contractorAuditService.selectContractorAuditIdsByName(getPara("contractorName"));
            if (contractorAuditIds.isEmpty()) {
                criteria.andIdIsNull();
            } else {
                criteria.andContractorAuditIdIn(contractorAuditIds);
            }
        }
        if (StringUtils.isNotEmpty(getPara("managerName"))) {
            List<String> staffIds = contractorStaffService.selectIdsByName(getPara("managerName"));
            if (staffIds.isEmpty()) {
                criteria.andIdIsNull();
            } else {
                criteria.andManagerIdIn(staffIds);
            }
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMin"))) {
            criteria.andAddTimeGreaterThanOrEqualTo(getPara("addTimeMin"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMax"))) {
            criteria.andAddTimeLessThanOrEqualTo(getPara("addTimeMax"));
        }
        if (StringUtils.isNotEmpty(getPara("addUserId"))) {
            criteria.andAddUserIdEqualTo(getPara("addUserId"));
        }
        if (StringUtils.isNotEmpty(getPara("addDeptId"))) {
            criteria.andAddDeptIdEqualTo(getPara("addDeptId"));
        }
        List<String> deptIds = dataAuthorityService.selectDataDeptIdByUserIdAndDeptId(getSessionUser().getId()
                , getSessionUser().getDepartment().getId());
        if (!deptIds.isEmpty()) {
            criteria.andAddDeptIdIn(deptIds);
        }
    }
}
